<template>
    <div class="co-cashier-page">
        <div class="box-row">
            <div class="box-full">
                <div class="co-toolbar box-row">
                    <el-select v-model="query.store_id" @change="onSelectStore" style="width: 150px;">
                        <el-option
                            v-for="item in stores"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                    <div>
                        <el-input size="default" v-model="query.code" placeholder="搜索商品" style="width:12rem" @clear="onSearch" clearable></el-input>
                    </div>
                    <div><el-button size="default" type="primary" @click="onSearch">查找</el-button></div>
                    <div style="flex:1"></div>
                    <el-button size="default" type="primary" @click="onReturnSales">退货</el-button>
                </div>
                <div class="ui-data-list-panel" v-loading="loading">
                    <el-tabs v-model="query.cat_id" @tab-click="onTabClick">
                        <el-tab-pane v-for="item in categorys" :label="item.name" :name="item.id"></el-tab-pane>
                    </el-tabs>
                    <el-scrollbar :height="sizes.tbHeight + 'px'">
                        <div class="ui-cashier-container" :style="{width:sizes.w + 'px'}">
                            <template v-for="item in data" :key="item.id">
                                <UICashierItem
                                    :goods="item"
                                    :width="sizes.w"
                                    @click="onItemClicked(item)"
                                ></UICashierItem>
                            </template>
                        </div>
                    </el-scrollbar>
                    <div class="ui-pagination-ctn">
                        <el-pagination :page-size="query.limit" :current-page="query.page" @current-change="onCurrentPageChanged" @size-change="onPageSizeChange" :page-sizes="[23, 50, 100, 200]" layout="sizes, total, prev, pager, next" :total="total"></el-pagination>
                    </div>
                </div>
            </div>
            <div class="co-cashier-info">
                <div v-if="selected.length">
                    <el-scrollbar :height="sizes.h + 'px'">  
                        <div v-for="(item,index) in selected" :key="item.id" class="selected">
                            <div class="selected-head">
                                <div class="name">{{ item.name }}</div>
                                <el-icon @click="onCloseGoods(index)"><CloseBold /></el-icon>
                            </div>
                            <div class="amount">单价：{{ item.sale_price }}元 \ 小计：{{ item.give ? 0 : item.sale_price * item.num }}元</div>
                            <div class="num">
                                <div>
                                    <el-checkbox 
                                        v-model="item.give" 
                                        label="赠送"
                                        size="large" 
                                        @change="onGiveChange(index)"
                                    />
                                </div>
                                <div>
                                    <el-input-number
                                        class="num-ipt"
                                        :min="1" 
                                        :max="item.store_num" 
                                        v-model="item.num" 
                                        :step="1"
                                        @change="onChangerNumber"
                                    ></el-input-number>
                                </div>
                            </div>
                        </div>
                    </el-scrollbar>
                    <div class="settlement">
                        <div class="wrap">
                            <div class="box-row" style="align-items: baseline;">
                                <div class="amount">总金额：{{ realpay.toFixed(2) }}元</div>
                                <div style="flex:1"></div>
                                <template v-if="desc != ''">
                                    <el-tooltip :content="'备注内容: '+desc" placement="top">
                                        <el-link type="primary" @click="onCheckChange">有备注</el-link>
                                    </el-tooltip>
                                </template>
                                <el-link v-else @click="onCheckChange">无备注</el-link>
                            </div>
                            <div class="btn">
                                <el-button-group class="button-group">
                                    <el-button type="success" @click="payment(4,2)">用户扫码</el-button>
                                    <el-popover
                                        placement="bottom"
                                        :width="200"
                                        trigger="click"
                                        v-if="allow_mb"
                                    >
                                        <template #reference>
                                            <el-button class="ui-dropdown-btn" type="success">
                                                <i class="ui-ico-arrow-down"></i>
                                            </el-button>
                                        </template>
                                        <el-link @click="payment(5,2)">会员卡余额收款</el-link>
                                    </el-popover>
                                    <el-button type="primary" @click="payment(4,1)">扫码收款</el-button>
                                    <el-button type="danger" @click="payment(3, 0)">现金收款</el-button>
                                </el-button-group>
                            </div>
                        </div>
                    </div>
                </div>
                <el-empty v-else description="未选择商品" />
            </div>
        </div>
    </div>
    <el-drawer
        v-model="drawer"
        direction="btt"
        title="请填写备注"
        class="drawer-order-desc"
        :before-close="onCloseDrawer"
    >
        <el-input
            v-model="desc"
            type="textarea"
            placeholder="这里填写订单备注..."
            :minlength="0" 
            :maxlength="200" 
            :rows="5" 
            class="desc-textarea"
        />
        <div style="margin-top:10px;display: flex;justify-content: space-between;">
            <el-button type="danger" @click="onCloseDesc">清空</el-button>
            <el-button type="primary" @click="onCloseDrawer">提交</el-button>
        </div>
    </el-drawer>
</template>
<script>
import { reactive, ref, toRefs, computed,onMounted,onUnmounted } from 'vue';
import { Session, UIMode } from '../uiframe/services/session';
import { useSocket } from '../uiframe/services/socket';
import { ElMessage, ElMessageBox } from 'element-plus';
import UICashierItem from './cashier/UICashierItem.vue';
import ScanPayDialog from './dialog/ScanPayDialog.vue';
import QrCodeDialog from './dialog/QrCodeDialog.vue';
import ReturnSalesDialog from './dialog/ReturnSalesDialog.vue';
import { CloseBold } from '@element-plus/icons-vue';
import { UiShowDialog } from '../uiframe/layout/components/CompFactory.vue';

export default {
    components:{
        UICashierItem,
        CloseBold
    },
    setup(props){
        let data = reactive({
            data: [],
            query: {
                on_sale:1,
                code: '', 
                limit: 23,
                page: 1
            },
            stores:[],
            categorys:[],
            allow_mb:false,
            visible:false,  // 控制显示网费收款弹出框
            desc:"",
            amount:0,
            realpay:0,
            drawer:false,
            loading:true,
            total: 0,
            sizes: computed(() => {
                let h = UIMode.mh.value,w = UIMode.mw.value;
                return {
                    tbHeight: h - 34 - 48 - 54,
                    w: w - 234 - 290,
                    h:h - 105
                }
            }),
            selected:[]
        })
        const load = () => {
            useSocket().then(socket=>{
                socket.rpc('category',{}).then(({success, data:result})=>{
                    if(success){
                        data.categorys = result;
                        if(!data.query.cat_id){
                            data.query.cat_id = result[0].id;
                        }
                        onSearch()
                    }
                })
            })
        }
        const onSearch = () => {
            data.loading = true
            useSocket().then(socket=>{
                socket.rpc('stores',{}).then(res=>{
                    if(!data.stores.length){
                        let s = [];
                        res.data?.forEach(v=>{
                            if(v.prop == 1){
                                s.push(v);
                            }
                        })
                        data.stores = s;
                        data.query.store_id = s[0]?.id;
                    }
                    socket.rpc('StoreComponents',data.query).then(({success, data:result})=>{
                        data.data = result.data;
                        data.total = result.total;
                        data.loading = false;
                    })
                })
            })
        },
        onmessage = (msg) => { ElMessage({ type: msg.success ? 'success' : 'error', message: msg.message }) },
        onBuyGoodsInit = ()=>{
            data.selected = [];
            data.desc = "";
            data.amount = 0;
            data.realpay = 0;
            onSearch();
        },
        methods = {
            onCurrentPageChanged:(page) => {
                data.query.page = page;
                onSearch();
            },
            onPageSizeChange:(limit) => {
                data.query.limit = limit;
                onSearch();
            },
            onSelectStore:(v)=>{
                data.selected = [];
                onSearch();
            },
            ChangeAllowMb:()=>{
                let mb = true;
                data.selected?.forEach(v=>{
                    if(!v.allow_mb){
                        mb = false;
                        return;
                    }   
                })
                data.allow_mb = mb;
            },
            onItemClicked:(goods)=>{
                if(goods.store_num == 0) return;
                let i = data.selected.findIndex(v=>goods.id == v.id && !v.give);
                data.amount = data.amount + goods.sale_price;
                data.realpay = data.realpay + goods.sale_price;
                let payload = {
                    id:goods.id,
                    store_id:goods.store_id,
                    name:goods.name,
                    sale_price:goods.sale_price,
                    num:1,
                    give:false,
                    store_num:goods.store_num,
                    allow_mb:goods.allow_mb
                };
                if(-1 !== i){
                    if(data.selected[i].give){
                        data.selected.push(payload);
                    }else{
                        data.selected[i].num++;
                    }
                }else{
                    data.selected.push(payload);
                }
                methods.ChangeAllowMb()
            },
            onGiveChange:(i)=>{
                let goods = data.selected[i];
                if(goods.give){
                    data.realpay -= goods.num * goods.sale_price;
                }else{
                    data.realpay += goods.num * goods.sale_price;
                }
            },
            onCloseGoods:(i) => {
                if(!data.selected[i].give){
                    data.realpay -= data.selected[i].num * data.selected[i].sale_price;
                }
                data.amount -= data.selected[i].num * data.selected[i].sale_price;
                data.selected.splice(i,1)
                methods.ChangeAllowMb()
            },
            onTabClick:()=> onSearch(),
            onChangerNumber:() => {
                let am = 0,rm = 0;
                data.selected.forEach(v=>{
                    if(!v.give) am += v.num * v.sale_price;
                    rm += v.num * v.sale_price;
                })
                data.amount =  rm;
                data.realpay = am;
            },
            onCheckChange:() => {
                data.drawer = true;
            },
            onCloseDrawer:() => {
                data.drawer = false;
            },
            onCloseDesc:()=>{
                data.desc = '';
            },
            payment:(mode, pay_mode) => {

                let payload = {
                    store_id:data.query.store_id,
                    settle_mode:mode,           // 0 挂账 3 现金 4 线上交易 5 会员卡（网吧计费卡）
                    pay_mode:pay_mode,          // 付款方式 0 无 1 付款码 2 展示二维码
                    desc:data.desc,             // 订单备注
                    realpay:data.realpay,       // 实付金额
                    amount:data.amount,         // 应付金额
                    scene: 1                    // 吧台
                }
                let g = [];
                data.selected.forEach(v=>{
                    console.log(v);
                    g.push({store_id: v.store_id, id:v.id,num:v.num,give:v.give,sale_price:v.sale_price})
                })
                payload.goods = g;
            
                useSocket().then(socket=>{
                    if(mode == 4){ //线上交易|会员卡
                        UiShowDialog(pay_mode==1 ? ScanPayDialog : QrCodeDialog, {
                            onSuccess:(auth_code, timeout)=>{
                            if(auth_code) payload.auth_code = auth_code;
                            payload.timeout = timeout;
                            return socket.rpc('sale',payload, Math.floor(timeout + 3) * 1000);
                        }}).then(res => {
                        
                        }).catch(res => {

                        })
                    }else if(mode == 5){ // 会员卡
                        UiShowDialog(QrCodeDialog, {
                            onSuccess:(auth_code, timeout)=>{
                            if(auth_code) payload.auth_code = auth_code;
                            payload.timeout = timeout;
                            return socket.rpc('sale',payload, Math.floor(timeout + 3) * 1000);
                        }}).then(res => {
                            onmessage({success:true,message:'付款成功.'})
                            if(res.success){
                                onBuyGoodsInit()
                            }
                        }).catch(res => {
                            
                        })
                    }else if(mode == 3){ //现金
                        ElMessageBox.confirm(`请收取现金: ${data.realpay.toFixed(2)} 元后点击确认.`).then(()=>{
                            socket.rpc('sale',payload).then(res=>{
                                onmessage(res);
                                if(res.success){
                                    onBuyGoodsInit()
                                }
                            })
                        }).catch(()=>{})
                    }
                })
            },
            onReturnSales:()=>{
                UiShowDialog(ReturnSalesDialog, {}).then(res => {
                
                }).catch(res => {

                })
            }
        }
        
        load();

        onMounted(() => {
            useSocket().then(socket=>{
                socket.watchSync('page-store-goods', [
                    {
                        'StoreComponents':(n) => n == 'up' || n == 'put',
                        _get:true
                    },{
                        'Goods':((n)=>n == 'put'), 
                        _get:true
                    }
                ],({StoreComponents,Goods})=>{
                    if(Goods){
                        Goods.store_num = 0;
                        Goods.sgid = 0;
                        data.data.push(Goods)
                    }

                    if(StoreComponents){
                        data.data.forEach(v => {
                            if((v.sgid == StoreComponents.id || v.id == StoreComponents.goods_id)){
                                for(let key in StoreComponents) {
                                    if(key == 'id') {
                                        v.sgid = StoreComponents[key];
                                    }else{
                                        v[key] = StoreComponents[key];
                                    }
                                }
                            }
                        })
                    }
                })
            })
        })

        onUnmounted(() => {
            useSocket().then(socket=>socket.unbind('page-store-goods'))
        })

        return {
            ...toRefs(data),
            ...methods,
            onSearch
        }
    }
}
</script>
<style lang="scss">
.co-cashier-page {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    user-select: none;
    .co-toolbar{
        border-bottom: 1px solid var(--el-border-color);
    }
    .ui-data-list-panel{
        padding-left:.5rem;
    }
    .ui-cashier-container{
        display: flex;
        flex-flow: wrap;
    }
    .co-cashier-info{
        width: 289px;
        border-left: 1px solid var(--el-border-color);
        .el-empty{
            height: 100%;
        }
        .selected{
            margin: .5rem;
            background-color: var(--el-border-color);
            border-radius: .25rem;
            padding: .5rem;
            .selected-head{
                display: flex;
                .name{
                    width:90%;
                    font-weight: 600;
                    overflow: hidden;
                    text-overflow:ellipsis;
                    white-space: nowrap;
                }
                .el-icon{
                    width:10%;
                    text-align: right;
                    cursor: pointer;
                }
            }
            .amount{
                font-size: 14px;
                margin: 10px 0;
            }
            .num{
                display: flex;
                justify-content: space-between;
                align-items: center;
                .num-ipt{
                    max-width: 8rem;
                }
            }
        }
        .settlement{
            position: fixed;
            bottom: 0;
            width: 289px;
            padding-bottom: 20px;
            background-color: #fff;
            .wrap{
                border-top: 1px solid var(--el-border-color);
                padding-top: 20px;
                margin: 0 .5rem;
                .amount{
                    padding-bottom: 20px;
                    font-size: 14px;
                    font-weight: 600;
                }
                .btn{
                    display: flex;
                    justify-content: center;
                }
            }
        }
    }
}
.drawer-order-desc{
    width: 289px!important;
    right: 0!important;
    left: auto!important;
}
.desc-textarea{
    .el-textarea__inner{
        resize: none;
    }
}
.ui-dropdown-btn{
    width: 30px;
}
.button-group{
    .el-button{
        font-size: 12px;
    }
}
</style>